package logic

import (
	"context"
	"fmt"
	"zhaowei/models/cache"
	"zhaowei/models/mysql"

	"zhaowei/baidurpc/baidurpc"
	"zhaowei/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *baidurpc.RegisterRequest) (*baidurpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("该手机号已被注册")
	}
	get, _ := cache.Rdb.Get(cache.Ctx, "sendsms"+in.Mobile).Result()
	if get != in.SendSms {
		return nil, fmt.Errorf("验证码错误")
	}
	user.Username = in.Username
	user.Mobile = in.Mobile
	user.Password = in.Password
	mysql.DB.Debug().Create(&user)
	return &baidurpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
